package com.lyw.GeoLocationClient.ui.adapter;

import android.content.*;
import android.util.*;
import android.view.*;
import android.widget.*;
import com.lyw.GeoLocationClient.R;
import com.lyw.GeoLocationClient.ui.GeotableItem;

import java.util.ArrayList;

public class ItemListAdapter extends BaseAdapter implements Filterable {
    private final String TAG = ItemListAdapter.class.getCanonicalName();
    private Context mContext;
	private boolean actionModeStarted;

    private Filter mFilter;

    private ArrayList<GeotableItem> mGeotableItemList;
    private ArrayList<GeotableItem> mOriginalValues;
//    private Boolean[] itemState;

    public boolean isChange() {
        return mChange;
    }

    private boolean mChange;

	public ItemListAdapter(Context context) {
		mContext = context;
        mGeotableItemList = new ArrayList<GeotableItem>();
    }

    public ItemListAdapter(Context context, ArrayList<GeotableItem> list) {
        this(context);
        update(list);
    }


	public int getCount() {
		return mGeotableItemList.size();
	}

	@Override
	public boolean areAllItemsEnabled() {
		return false;
	}

//	@Override
//	public boolean isEnabled(int position) {
//		return !mItemList.get(position).startsWith("-");
//	}

	public Object getItem(int position) {
		return mGeotableItemList.get(position);
	}

	public long getItemId(int position) {
        return position;
    }

	public View getView(int position, View v, ViewGroup parent) {

        ItemLayout il = v == null ? new ItemLayout(mContext)
                : (ItemLayout) v;

        GeotableItem geotableItem = mGeotableItemList.get(position);
        il.setTag(geotableItem.getTitle());

        il.mTitle.setText(geotableItem.getTitle());
        il.mTitle.setTextColor(mContext.getResources().getColor(geotableItem.getColor()));

        il.mCheckBox.setVisibility(View.VISIBLE);
        il.mImage.setImageResource(geotableItem.getIconRes());
//            updateBackground(position , il);
        updateCheckBox(position, il.mCheckBox);

        return il;
	}

	public void updateBackground(int position, View view) {
//		int backgroundId;
//        if (itemState[position]) {
//            backgroundId = R.drawable.list_selected_holo_light;
//        } else {
//            backgroundId = R.drawable.conversation_item_background_read;
//        }
//        Drawable background = mContext.getResources().getDrawable(backgroundId);
//        view.setBackground(background);
	}

    public void checkItem(int position) {
        mGeotableItemList.get(position).setActive(!mGeotableItemList.get(position).isActive());
//        itemState[position] = !itemState[position];
        mChange = true;
        notifyDataSetChanged();
    }

    public void updateCheckBox(int position, CheckBox view) {
        view.setChecked(mGeotableItemList.get(position).isActive());
    }

	
	public void setActionModeState(boolean flag){
		actionModeStarted = flag;
        notifyDataSetChanged();
	}
	
	public boolean isActionModeStart(){
		return actionModeStarted;
	}


    public void update(ArrayList<GeotableItem> lists) {
        LOG("update " + lists);
//        mItemList.clear();
//        for (Item file : lists) {
//            mItemList.add(file);
//        }
//        if (lists.size() == mItemList.size()) {
//            return;
//        }
        mGeotableItemList = lists;
//        notifyDataSetChanged();
    }

    public ArrayList<GeotableItem> getSelectItems() {
        ArrayList<GeotableItem> list = new ArrayList<GeotableItem>();
//        for (int i = 0; i < itemState.length; i++) {
//            LOG("i " + i + " " + itemState[i]);
//            if (itemState[i]) {
//                LOG("add i " + i);
//                files.add(mItemList.get(i));
//            }
//        }
        for (GeotableItem geotableItem : mGeotableItemList) {
            if (geotableItem.isActive()) {
                list.add(geotableItem);
            }
        }
        mChange = false;
        return list;
    }

    class ViewHolder {

    }

    private class ItemLayout extends LinearLayout {
        TextView mTitle;

        CheckBox mCheckBox;
        ImageView mImage;

        public ItemLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public ItemLayout(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }

        public ItemLayout(Context context) {
            super(context);
            LayoutInflater.from(context).inflate(
                    R.layout.item_row_list, this, true);

            mTitle = (TextView) findViewById(R.id.item_title);
            mCheckBox = (CheckBox) findViewById(R.id.item_checkbox);
            mImage = (ImageView) findViewById(R.id.item_icon);
        }
    }


    public Filter getFilter() {
        if (mFilter == null) {
            mFilter = new FilesFilter();
        }
        return mFilter;
    }

    private final Object mLock = new Object();

    private class FilesFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence prefix) {
            FilterResults results = new FilterResults();
            if (mOriginalValues == null) {
                synchronized (mLock) {
                    mOriginalValues = new ArrayList<GeotableItem>(mGeotableItemList);
                }
            }

            if (prefix == null || prefix.length() == 0) {
                ArrayList<GeotableItem> list;
                synchronized (mLock) {
//                    list = new ArrayList<Item>(RecordManager.getManager().getSortedFileList());
                }
//                results.values = list;
//                results.count = list.size();
            } else {
                String prefixString = prefix.toString().toLowerCase();

                ArrayList<GeotableItem> values;
                synchronized (mLock) {
                    values = new ArrayList<GeotableItem>(mOriginalValues);
                }

                final int count = values.size();
                final ArrayList<GeotableItem> newValues = new ArrayList<GeotableItem>();

                for (int i = 0; i < count; i++) {
                    final GeotableItem value = values.get(i);
                    final String valueText = value.toString().toLowerCase();

                    // First match against the whole, non-splitted value
                    if (valueText.contains(prefixString)) {
                        newValues.add(value);
                    } else {
                        final String[] words = valueText.split(" ");
                        final int wordCount = words.length;

                        // Start at index 0, in case valueText starts with space(s)
                        for (int k = 0; k < wordCount; k++) {
                            if (words[k].contains(prefixString)) {
                                newValues.add(value);
                                break;
                            }
                        }
                    }
                }

//                results.values = RecordManager.getManager().sort(newValues);
                results.count = newValues.size();
            }

            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            //noinspection unchecked
            mGeotableItemList = (ArrayList<GeotableItem>) results.values;
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }

    private void LOG(String msg) {
//        if (DEBUG)
            Log.d(TAG, msg);
    }

}
